import { Notice } from '../models';

export default function (router) {
  /**
   * 前端获取通知列表
   */
  router.get('/api/front/notice', async ctx => {
    const { userid } = ctx.state.user || {};
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const orParams = [];
    userid && orParams.push({ user: { $regex: `.*${userid}.*` } });
    orParams.push({ user: 'all' });
    const userAgent = ctx.request.headers['user-agent'];
    if (/Android/i.test(userAgent)) {
      orParams.push({ user: 'android' });
    }
    if (/iPhone|iPad|iPod/i.test(userAgent)) {
      orParams.push({ user: 'ios' });
    }
    const total = await Notice.countDocuments({
      $or: orParams
    });
    const notices = await Notice.find(
      {
        $or: orParams
      },
      '-content'
    )
      .skip((page - 1) * 10)
      .limit(limit)
      .sort({ create_time: -1 });
    await ctx.json(true, 'success', { list: notices, total });
  });

  /**
   * 前端获取最新通知列表
   * 用来刷新通知提醒
   */
  router.get('/api/front/notice/flush', async ctx => {
    const { userid } = ctx.state.user || {};
    const orParams = [];
    userid && orParams.push({ user: { $regex: `.*${userid}.*` } });
    orParams.push({ user: 'all' });
    const userAgent = ctx.request.headers['user-agent'];
    if (/Android/i.test(userAgent)) {
      orParams.push({ user: 'android' });
    }
    if (/iPhone|iPad|iPod/i.test(userAgent)) {
      orParams.push({ user: 'ios' });
    }
    const lastWeek = new Date();
    lastWeek.setDate(lastWeek.getDate() - 7);
    const notices = await Notice.find(
      {
        $or: orParams,
        create_time: { $gte: lastWeek }
      },
      'id'
    ).sort({ create_time: -1 });
    await ctx.json(true, 'success', { list: notices });
  });

  /**
   * 前端获取通知详情
   */
  router.get('/api/front/notice/:id/detail', async ctx => {
    // if (!ctx.state.user) {
    //   await ctx.noLogin();
    //   next();
    //   return;
    // }
    const { id } = ctx.params;
    const thisNotice = await Notice.findById(id);
    if (thisNotice) {
      await ctx.json(true, 'success', thisNotice);
    } else {
      await ctx.json(false, '获取通知详情失败');
    }
  });

  /**
   * 后台获取通知列表
   */
  router.get('/api/admin/notice', async ctx => {
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const { search } = ctx.request.query;
    const queryParam = {};
    queryParam.type = 'system';
    if (search) {
      const reg = new RegExp(search.toString('utf8').trim(), 'i');
      queryParam.$or = [{ title: reg }, { description: reg }];
    }
    const total = await Notice.countDocuments(queryParam);
    const notices = await Notice.find(queryParam)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ create_time: -1 });
    await ctx.json(true, 'success', { list: notices, total });
  });

  /**
   * 后台获取通知详情
   */
  router.get('/api/admin/notice/:id/detail', async ctx => {
    const id = ctx.params.id;
    const thisNotice = await Notice.findById(id);
    if (thisNotice) {
      await ctx.json(true, 'success', thisNotice);
    } else {
      await ctx.json(false, '获取通知详情失败');
    }
  });

  /**
   * 后台新增通知
   */
  router.post('/api/admin/notice', async ctx => {
    const { title = '', description = '', content = '', preview = '', users = '', previewImg = '' } = ctx.request.body;
    if (!users) {
      await ctx.json(false, '发送用户不能为空');
      return;
    }
    if (!title) {
      await ctx.json(false, '标题不能为空');
      return;
    }
    if (!description) {
      await ctx.json(false, '描述不能为空');
      return;
    }
    if (!content) {
      await ctx.json(false, '内容不能为空');
      return;
    }

    const notice = await Notice.create({
      user: users,
      type: 'system',
      title,
      description,
      content,
      preview,
      previewImg,
      create_time: new Date()
    });
    await ctx.json(true, 'success', notice);
  });

  /**
   * 后台修改通知
   */
  router.put('/api/admin/notice/:id', async ctx => {
    const id = ctx.params.id;
    if (!id) {
      await ctx.json(false, '参数错误');
      return;
    }
    const { title = '', description = '', content = '', preview = '', users = '', previewImg = '' } = ctx.request.body;
    if (!users) {
      await ctx.json(false, '发送用户不能为空');
      return;
    }
    if (!title) {
      await ctx.json(false, '标题不能为空');
      return;
    }
    if (!description) {
      await ctx.json(false, '描述不能为空');
      return;
    }
    if (!content) {
      await ctx.json(false, '内容不能为空');
      return;
    }
    const thisNotice = await Notice.findById(id, '_id');
    if (!thisNotice) {
      await ctx.json(false, '找不到该通知');
      return false;
    }

    const updateResult = await Notice.updateOne(
      { _id: id },
      {
        $set: {
          title,
          description,
          content,
          preview,
          previewImg,
          user: users
        }
      }
    );
    if (updateResult.ok) {
      await ctx.json(true, 'success');
    } else {
      await ctx.json(false, '更新通知失败');
    }
  });

  /**
   * 后台删除通知
   */
  router.delete('/api/admin/notice/:id', async ctx => {
    const id = ctx.params.id;
    if (!id) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const thisNotice = await Notice.findById(id, '_id');
    if (!thisNotice) {
      await ctx.json(false, '找不到该通知');
      return false;
    }
    const deleteResult = await Notice.deleteOne({ _id: id });
    if (deleteResult.ok) {
      await ctx.json(true, 'success');
    } else {
      await ctx.json(false, '删除通知失败');
    }
  });
}
